using System;
using System.Collections.Generic;
using UMC.Data;
using UMC.Web;

using UMC.WorkFlow.Entities;

namespace UMC.WorkFlow
{


    [Apiumc("WorkFlow", "Publish", Auth = WebAuthType.Admin, Desc = "流程发布同步")]
    public class DesignPublishActivity : WebActivity
    {
        public override void ProcessActivity(WebRequest request, WebResponse response)
        {
            var Task = UMC.Data.Utility.UInt64Parse(this.AsyncDialog("Task", g =>
             {
                 this.Prompt("请传入表单");
                 return this.DialogValue("none");
             })) ?? 0;
            var SId = this.AsyncDialog("Id", "default");

            var design = DataFactory.Instance().TaskDesign(Task);

            if (design == null)
            {
                this.Prompt("无此流程设计");
            }

            var es = HotCache.Search<TaskObSerialize>().Unequal(new TaskObSerialize
            {
                Status = TaskStatus.Completed
            }).Query(new TaskObSerialize { TaskId = design.TaskId }, false, 0, 10000, out var outIndex);
            

            this.AsyncDialog("Confirm", g => new UIConfirmDialog(String.Format("有{0}条未完成的流程，点击确认将会更新流程", es.Length)));

            var taskInstance = UMC.Data.JSON.Deserialize<TaskInstance>(design.Context);

            foreach (var e in es)
            {
                var taskInstance2 = UMC.Data.JSON.Deserialize<TaskInstance>(e.SerializeData);
                var stas = taskInstance2.Shapes.FindAll(g => g.Status == ShapeStatus.Unactivated);
                foreach (var us in stas)
                {
                    var s = taskInstance.Shapes.Find(g => g.Id == us.Id);
                    if (s != null)
                    {
                        s.Status = ShapeStatus.Unactivated;
                        taskInstance2.Shapes.Remove(us);
                        taskInstance2.Shapes.Add(s);
                    }
                }

                var lines = taskInstance2.Lines.FindAll(g => g.Status == LineStatus.UnPass);
                foreach (var us in lines)
                {
                    var s = taskInstance.Lines.Find(g => g.Id == us.Id);
                    if (s != null)
                    {
                        s.Status = LineStatus.UnPass;
                        taskInstance2.Lines.Remove(us);
                        taskInstance2.Lines.Add(s);
                    }
                }
                taskInstance2.Registes.Clear();
                taskInstance2.Registes.AddRange(taskInstance.Registes);


                taskInstance2.Induces.Clear();
                taskInstance2.Induces.AddRange(taskInstance.Induces);
                DataFactory.Instance().Put(new TaskObSerialize { InstanceId = e.InstanceId, SerializeData = UMC.Data.JSON.Serialize(taskInstance2, true) });


            }
            this.Prompt(String.Format("成功更新{0}条", es.Length));




        }
    }
}